package vip.xls8z.learning.bio.server;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.UUID;

@Slf4j
public class BioEchoHandler implements Runnable {

    private final Socket socketClient;

    public BioEchoHandler(Socket socketClient) {
        this.socketClient = socketClient;
    }

    @Override
    public void run() {
        try {
            while (true) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
                PrintStream writer = new PrintStream(socketClient.getOutputStream());

                String message = reader.readLine();
                log.info("CLIENT: {}", message);
                if (message.equalsIgnoreCase("bye")) {
                    writer.println("EXIT");
                    log.info("[SERVER]: {}", "EXIT");

                    writer.close();
                    reader.close();
                    break;
                }

                String replyMsg = "reply message " + UUID.randomUUID();
                writer.println(replyMsg);
                log.info("[SERVER]: {}", replyMsg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}